<template>
  <div class="activity">
    <div id="qrcode"></div>
    <el-form :inline="true" :model="queryForm" class="demo-form-inline">
      <el-form-item label="活动名称：">
        <el-input
          v-model="queryForm.name"
          placeholder="请输入活动名称"
          clearable
        ></el-input>
      </el-form-item>
      <el-form-item label="类型：">
        <el-select
          @change="seachData"
          v-model="queryForm.type"
          placeholder="请选择类型"
          clearable
        >
          <el-option label="全部" :value="null"></el-option>
          <el-option
            v-for="(item, index) in selectEnums.type"
            :key="index"
            :label="item.label"
            :value="item.value"
          ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="年级：">
        <el-select
          @change="seachData"
          v-model="queryForm.grade"
          placeholder="请选择年级"
          clearable
        >
          <el-option label="全部" :value="null"></el-option>
          <el-option
            v-for="(item, index) in selectEnums.grade"
            :key="index"
            :label="item.label"
            :value="item.value"
          ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="状态：">
        <el-select
          @change="seachData"
          v-model="queryForm.status"
          placeholder="请选择所属科目"
          clearable
        >
          <el-option label="全部" :value="null"></el-option>
          <el-option label="关闭" :value="0"></el-option>
          <el-option label="开启" :value="1"></el-option>
          <el-option label="已结束" :value="2"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="seachData()">搜索</el-button>
        <el-button type="primary" @click="addActivity()">新增活动</el-button>
      </el-form-item>
    </el-form>
    <el-table
      :data="tableData"
      border
      style="width: 100%"
      header-cell-class-name="thead"
      @row-click="toView"
    >
      <el-table-column prop="name" label="活动名称"></el-table-column>
      <el-table-column prop="date" label="活动时间" width="250">
        <template slot-scope="scope">
          <p>开始：{{ scope.row.start_time.substring(0, 16) }}</p>
          <p>结束：{{ scope.row.end_time.substring(0, 16) }}</p>
        </template>
      </el-table-column>
      <el-table-column label="类型" align="center">
        <template slot-scope="scope">
          <p>{{ scope.row.type | G(selectEnums.type) }}</p>
        </template>
      </el-table-column>
      <el-table-column prop="date" label="所属年级" align="center">
        <template slot-scope="scope">
          <p>{{ scope.row.grade | G(selectEnums.grade) }}</p>
        </template>
      </el-table-column>
      <el-table-column label="实付总金额" width="300" align="center">
        <template slot-scope="scope">
          <b>{{ scope.row.total_amount }}</b>
        </template>
      </el-table-column>
      <el-table-column prop="order_count" label="订单数" align="center">
        <template slot-scope="scope">
          <b>{{ scope.row.order_count }}</b>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" width="150">
        <template slot-scope="scope">
          <div @click.stop="1">
            <el-switch
              v-model="scope.row.status"
              active-color="#13c2c2"
              inactive-color="#ccc"
              @change="switchChange($event, scope.row)"
              :disabled="scope.row.disabled"
            />
          </div>
          <el-button size="small" type="text">
            <a @click.stop="downLoad(scope.row)">下载码</a></el-button
          >
          <el-button size="small" type="text" @click.stop="copyUrl(scope.row)"
            >复制链接</el-button
          >
        </template>
      </el-table-column>
    </el-table>
    <el-pagination
      @size-change="sizeChangeHandle"
      @current-change="currentChangeHandle"
      :current-page="pageIndex"
      :page-sizes="[10, 20, 50, 100]"
      :page-size="pageSize"
      :total="totalPage"
      layout="total, sizes, prev, pager, next, jumper"
    ></el-pagination>
    <div id="qscode" class="qscode" />
  </div>
</template>
<script>
import jquery from 'jquery'
import QRCode from 'qrcodejs2'
import {
  getActivityList,
  getActivityResource,
  openActivity,
  closeActivity
} from '@/api/coupon.js'
export default {
  data () {
    return {
      tableData: [],
      totalPage: 0,
      pageSize: 10,
      pageIndex: 1,
      selectEnums: {
        type: [],
        grade: []
      },
      queryForm: {
        name: '',
        type: '',
        grade: '',
        status: ''
      },
      qrcode: null
    }
  },
  activated () {
    this.getActivityResource()
  },
  // created () {
  //   this.getActivityResource()
  // },
  filters: {
    G (value, data) {
      let res = data.filter(ele => {
        return ele.value === value
      })
      if (res.length) {
        return res[0].label
      } else {
        return ''
      }
    }
  },
  methods: {
    async getActivityResource () {
      let res = await getActivityResource({})
      if (res[0]) {
        return
      }
      if (res[1].code === 0) {
        let arr = res[1].data
        Object.keys(this.selectEnums).forEach(item => {
          for (let i = 0; i < arr.length; i++) {
            if (arr[i].fieldName === item) {
              this.selectEnums[item] = arr[i].sourceData.child
            }
          }
        })
        this.selectEnums = JSON.parse(
          JSON.stringify(this.selectEnums)
            .split('display_value')
            .join('label')
            .split('t_id')
            .join('value')
        )
        this.getData()
      }
    },
    seachData () {
      this.pageIndex = 1
      this.getData()
    },
    async getData () {
      let res = await getActivityList({
        currPage: this.pageIndex,
        pageSize: this.pageSize,
        name: this.queryForm.name,
        type: this.queryForm.type,
        grade: this.queryForm.grade,
        status: this.queryForm.status
      })
      if (res[0]) {
        return
      }
      if (res[1].code === 0) {
        this.tableData = res[1].data.activityList
        this.totalPage = res[1].data.totalCount
        this.tableData.map(item => {
          let nowdate = new Date().getTime()
          let endTime = new Date(item.end_time).getTime()
          item.status = nowdate > endTime ? 2 : item.status
          item.disabled = item.status === 2
          item.status === 1 ? (item.status = true) : (item.status = false)
        })
      }
    },
    sizeChangeHandle (val) {
      this.pageSize = val
      this.pageIndex = 1
      this.getData()
    },
    // 下载
    downLoad (e, fileName = '活动二维码下载.png', content = '') {
      this.qrcode = new QRCode('qrcode', {
        width: 500,
        height: 500, // 高度
        text: e.url, // 二维码内容
        render: 'canvas' // 设置渲染方式（有两种方式 table和canvas，默认是canvas）
      })
      setTimeout(() => {
        let img = jquery('#qrcode').find('img')[0].src
        jquery('#qrcode img').remove()
        let aLink = document.createElement('a')
        let blob = this.base64ToBlob(img) // new Blob([content]);
        let evt = document.createEvent('HTMLEvents')
        evt.initEvent('click', true, true) // initEvent 不加后两个参数在FF下会报错  事件类型，是否冒泡，是否阻止浏览器的默认行为
        aLink.download = fileName
        aLink.href = URL.createObjectURL(blob)
        aLink.click()
      }, 800)
    },
    // 当前页
    currentChangeHandle (val) {
      this.pageIndex = val
      this.getData()
    },
    addActivity () {
      this.$router.push({
        name: 'add-activity',
        query: { mode: 'add' }
      })
    },
    toView (e) {
      this.$router.push({
        name: 'add-activity',
        query: { mode: 'view', id: e.id }
      })
    },
    base64ToBlob (code) {
      let parts = code.split(';base64,')
      let contentType = parts[0].split(':')[1]
      let raw = window.atob(parts[1])
      let rawLength = raw.length

      let uInt8Array = new Uint8Array(rawLength)

      for (let i = 0; i < rawLength; ++i) {
        uInt8Array[i] = raw.charCodeAt(i)
      }
      return new Blob([uInt8Array], { type: contentType })
    },
    copyUrl (row) {
      var Url2 = row.url
      var oInput = document.createElement('input')
      oInput.value = Url2
      document.body.appendChild(oInput)
      oInput.select() // 选择对象
      document.execCommand('Copy') // 执行浏览器复制命令
      oInput.className = 'oInput'
      oInput.style.display = 'none'
      this.$message({
        message: '复制成功!',
        type: 'success'
      })
    },
    async switchChange (e, row) {
      let res = e
        ? await openActivity({ id: row.id })
        : await closeActivity({ id: row.id })
      if (res[0]) {
        return
      }
      const data = res[1]
      if (data && data.code === 0) {
        this.$message.success('更改状态成功！')
        this.getData()
      } else {
        this.$message.error(data.msg)
      }
    }
  }
}
</script>

<style lang="scss" scoped>
#qrcode {
  display: none;
}
</style>
